package com.codeying.filter;

import com.codeying.entity.LoginUser;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
* 没有登录的用户，不可以访问页面
*/
@WebFilter(urlPatterns = {"/hello","/admin/*","/user/*","/car/*","/yuyue/*","/rentorder/*","/userComment/*","/notice/*"})
public class LoginFilter implements Filter{

    @Override
    public void destroy() {
        System.out.println("LoginFilter destroy....");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        LoginUser user=(LoginUser)req.getSession().getAttribute("user");
        if(user!=null) {
            chain.doFilter(request, response);
        }else {
            req.setAttribute("message","请先登录");
            req.getRequestDispatcher("/login.jsp").forward(req, response);
        }

    }

    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("LoginFilter init....");
    }

}

